package com.tianji.promotion.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 19311
 * @CreateTime: 2025-03-29
 * @Description: Redis锁
 * @Version: 1.0
 */
@RequiredArgsConstructor
public class RedisLock {

    private final String key;
    private final StringRedisTemplate redisTemplate;

    public boolean tryLock(Long leaseTime, TimeUnit unit) {
        // 1. 获取线程名称
        String value = Thread.currentThread().getName();

        // 2.获取锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "1", leaseTime, unit);

        // 自动拆箱情况有一个空指针的风险
        if (success == null) {
            return false;
        }
        // 3、返回结果
        return success;
    }

    public void unlock() {
        redisTemplate.delete(key);
    }
}
